package com.shebao.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PRIndirectReference;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.shebao.entity.SBUserEntity;

/**
 *
 * 单位全职员工 PDF 工具
 *
 * Created by Frank on 2017\12\21 0021.
 */
@Component
public class CompanyStuffPDFUtil {
	
	@Value("${file.outFile}")
	private String outFile;
	
	@Value("${img.waterMark1}")
	private String waterMark1;
	
    public static void main(String[] args) throws Exception {
        //水印形式（图片）生成PDF
//        imageWaterMark(createPDF(), "G:\\idea_work\\shebao\\src\\main\\resources/ssos.png");

        //水印形式（文字）生成PDF
//        stringWaterMark(createPDF(), "天恒志远");

        //普通生成
//        createPDF();

        //读文档；
//        readPDF();
//    	SBUserEntity s=new SBUserEntity();
//    	List<SBUserEntity> list=new ArrayList<SBUserEntity>();
//    	for(int i=0;i<29;i++){
//    		list.add(s);
//    	}
//    	createPDF(list);
    }

    public static void readPDF() throws Exception{
        String pdfPath = "C:\\Users\\Administrator\\Desktop\\test\\单位全职员工.pdf";

        PdfReader pdfReader = new PdfReader(pdfPath);

        PdfDictionary catalog = pdfReader.getCatalog();
        PdfDictionary acroform = catalog.getAsDict(PdfName.ACROFORM);

        PdfDictionary dr = acroform.getAsDict(PdfName.DR);
        PdfDictionary font = dr.getAsDict(PdfName.FONT);
        for (PdfName key : font.getKeys()) {
            System.out.println((PRIndirectReference)font.getAsIndirectObject(key));
        }


        pdfReader.close();


    }
    
    private void createHead(Document doc,Font textFont,Font numberFontBold,Font secondTitleFont,BaseFont bfChinese,Phrase phrase,Chunk companyKeyChunk
    		,Chunk companyValueChunk,PdfPCell cell,boolean isFirstPage) throws DocumentException{
    	
    	if(!isFirstPage){
    		PdfPTable tableTmp = new PdfPTable(3);
        	//设置列宽
        	tableTmp.setTotalWidth(new float[]{ 256, 258, 256 });
            //锁定列宽
        	tableTmp.setLockedWidth(true);
        	PdfPCell cellt=new PdfPCell();
        	cellt.setMinimumHeight(20);
        	cellt.setColspan(3);
        	cellt.setBorder(0);
        	tableTmp.addCell(cellt);
        	doc.add(tableTmp);
    	}
    	
    	
    	PdfPTable table = new PdfPTable(3);
        //设置列宽
        table.setTotalWidth(new float[]{ 256, 258, 256 });
        //锁定列宽
        table.setLockedWidth(true);

        Phrase titlePhrase = new Phrase("成都市社会保险人员花名册", secondTitleFont);
        cell = new PdfPCell(titlePhrase);

        //设置单元格高度
        cell.setMinimumHeight(32);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_TOP);
        cell.setBorder(0);
        cell.setColspan(3);
        table.addCell(cell);

        phrase.clear();
        companyKeyChunk = new Chunk("单位编码：", textFont);
        companyValueChunk = new Chunk("260186", textFont);
        phrase.add(companyKeyChunk);
        phrase.add(companyValueChunk);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(9);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("单位名称：鼎立九州质检技术服务有限公司", textFont));
        //设置单元格高度
        cell.setMinimumHeight(9);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);

        table.addCell(cell);

        cell = new PdfPCell(new Phrase("打印时间："+DateUtil.printDate(), textFont));
        //设置单元格高度
        cell.setMinimumHeight(9);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);

        cell.setBorder(0);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("注（人员缴费类别：01=城镇职工，02=原综合本市户籍农民工，03=非本市户籍农民工）", new Font(bfChinese,8, Font.NORMAL)));
        //设置单元格高度
        cell.setMinimumHeight(20);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        cell.setColspan(3);
        table.addCell(cell);

        doc.add(table);
    }
    /**
     * 创建PDF 文档
     * @return
     * @throws Exception
     */
    public String createPDF(List<SBUserEntity> list) throws Exception {

        //输出路径
        //DataUtil.createTempPath(".pdf");

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

        String outPath = outFile+"company-"+format.format(new Date())+".pdf";

        //设置纸张
        
        Rectangle rect = new Rectangle(new RectangleReadOnly(840,600));
        //创建文档实例
        Document doc = new Document(rect);

        //添加中文字体
        BaseFont bfHelvetica = BaseFont.createFont();

        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        /**
         * 设置字体样式
         */
        //正常
        Font textFont = new Font(bfChinese,11, Font.NORMAL);
        Font numberFontBold = new Font(bfHelvetica,10, Font.NORMAL);
        //二级标题
        Font secondTitleFont = new Font(bfChinese,18,Font.NORMAL);

        //创建输出流
        PdfWriter pdfWriter = PdfWriter.getInstance(doc, new FileOutputStream(new File(outPath)));
        int totalPage = (list.size()+25-1)/25;
        pdfWriter.setPageEvent(new PDFPageHelper(totalPage));

        doc.setMargins(0,0,20,1);

        doc.open();
        doc.newPage();

        doc.setMarginMirroringTopBottom(true);

        Phrase phrase = new Phrase();
        Chunk companyKeyChunk = null;
        Chunk companyValueChunk = null;
        PdfPCell cell = null;
        createHead(doc, textFont, numberFontBold, secondTitleFont, bfChinese,phrase,companyKeyChunk,companyValueChunk,cell,true);
        


        /**
         * 画表格
         */
        // 创建一个有20列的表格
        PdfPTable table  = createDataTable();

        drawTitle(bfChinese, table);
        Font fontDetail = new Font(bfChinese,8,Font.NORMAL);

        Font fontDetailNumber = new Font(bfChinese,8,Font.NORMAL);
        SBUserEntity entity=null;
        //模拟数据
        for(int i = 0;i<list.size();i++){
            //分页
        	boolean isTop=false;
            if (i != 0 && i%25 == 0){
                doc.add(table);

                doc.newPage();//创建新的页面
                createHead(doc, textFont, numberFontBold, secondTitleFont, bfChinese,phrase,companyKeyChunk,companyValueChunk,cell,false);
                table = createDataTable();
                drawTitle(bfChinese, table);
                isTop=true;
            }
            
            entity=list.get(i);
            createHeaderCell(table,new TableHeaderCell(""+entity.getId(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getSocialId(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getUserName(),16,1,1,fontDetail),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getCardId(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getSex(),16,1,1,fontDetail),false,isTop);
            createHeaderCell(table,new TableHeaderCell("0"+entity.getPayType()+"\u00a0\u00a0",16,1,1,fontDetail),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getWages(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getOldDate(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getOldBase(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getMedicalDate(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getMedicalType(),16,1,1,fontDetail),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getMedicalBase(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getUnemploymentDate(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getUnemploymentBase(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getHurtDate(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getHurtBase(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getBirthDate(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getBirthBase(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getSupplyDate(),16,1,1,fontDetailNumber),false,isTop);
            createHeaderCell(table,new TableHeaderCell(entity.getSupplyBase(),16,1,1,fontDetailNumber),true,isTop);
            
            if(list.size()==(i+1)){
            	doc.add(table);
            }
        }

        //最后的提示信息
        table = createDataTable();

        Font endFont = new Font(bfChinese,9, Font.NORMAL);
        phrase = new Phrase();
        companyKeyChunk = new Chunk("◆成都市社会保险参保查询专用章已经四川省数字证书认证管理中心认证，是对外出具参保缴费信息指定电子用章。", endFont);
        phrase.add(companyKeyChunk);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(9);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居左
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        cell.setColspan(20);
        table.addCell(cell);

        doc.add(table);

        doc.close();
        return imageWaterMark(outPath, waterMark1);
    }



    /**
     * 创建表头单元格和数据
     * @param table 表格对象
     * @param head 表头单元格
     */
    private void createHeaderCell(PdfPTable table,TableHeaderCell head) throws DocumentException, IOException {
    	createHeaderCell(table, head,false,false);
    }
    private void createHeaderCell(PdfPTable table,TableHeaderCell head,boolean isRight,boolean isTop) throws DocumentException, IOException {

        if (head == null || table == null){
            return ;
        }

        PdfPCell cell;
        //这里通过Phrase 居中
        Phrase phrase = new Phrase(head.getContent(), head.getFont());

        cell = new PdfPCell(phrase);
        
        //设置border
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);


        //设置单元格高度
        cell.setMinimumHeight(head.getCellHeight());
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        if(!isRight){
        	cell.disableBorderSide(8);// 隐藏单元格周边的右框
        }
        if(!isTop){
        	cell.disableBorderSide(1);// 隐藏单元格周边的上边框
        }
        
        cell.setBorderWidth(0.1f);
        //设置该单元格横跨的行数
        cell.setRowspan(head.getRowspan());
        //设置该单元格横跨的列数
        cell.setColspan(head.getColspan());
        table.addCell(cell);

    }

    /**
     * 创建单元格
     *
     * @param table
     * @param title
     * @param row
     * @param cols
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    private PdfPTable createCell(PdfPTable table, String[] title, int row, int cols) throws DocumentException, IOException {
        //添加中文字体
        BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(bfChinese,11,Font.BOLD);

        for(int i = 0; i < row; i++){

            for(int j = 0; j < cols; j++){

                PdfPCell cell = new PdfPCell();

                //设置表头
                if(i==0 && title!=null){
                    //这样表头才能居中
                    cell = new PdfPCell(new Phrase(title[j], font));
                    if(table.getRows().size() == 0){
                        cell.setBorderWidthTop(3);
                    }
                }

                //只有一行一列
                if(row==1 && cols==1){
                    cell.setBorderWidthTop(3);
                }

                //设置左边的边框宽度
                if(j==0){
                    cell.setBorderWidthLeft(3);
                }

                //设置右边的边框宽度
                if(j==(cols-1)){
                    cell.setBorderWidthRight(3);
                }

                //设置底部的边框宽度
                if(i==(row-1)){
                    cell.setBorderWidthBottom(3);
                }

                //设置单元格高度
                cell.setMinimumHeight(40);
                //设置可以居中
                cell.setUseAscender(true);
                //设置水平居中
                cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
                //设置垂直居中
                cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);

                table.addCell(cell);
            }
        }

        return table;
    }

    /**
     * 加水印（字符串）
     *
     * @param inputFile 需要加水印的PDF路径
     * @param waterMarkName 水印字符
     */
    public  void stringWaterMark(String inputFile, String waterMarkName) {
        try {
            String[] spe = PDFDataUtil.separatePath(inputFile);
            String outputFile = spe[0] + "_WM." + spe[1];

            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));


            //添加中文字体
            BaseFont bfChinese=BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);


            int total = reader.getNumberOfPages() + 1;


            PdfContentByte under;
            int j = waterMarkName.length();
            char c = 0;
            int rise = 0;
            //给每一页加水印
            for (int i = 1; i < total; i++) {
                rise = 400;
                under = stamper.getUnderContent(i);
                under.beginText();
                under.setFontAndSize(bfChinese, 30);
                under.setTextMatrix(200, 120);
                for (int k = 0; k < j; k++) {
                    under.setTextRise(rise);
                    c = waterMarkName.charAt(k);
                    under.showText(c + "");
                }


                // 添加水印文字
                under.endText();
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加水印（图片）
     *
     * @param inputFile 需要加水印的PDF路径
     * @param imageFile 水印图片路径
     */
    public  String imageWaterMark(String inputFile, String imageFile) {
    	String outputFile=null;
    	PdfReader reader=null;
    	PdfStamper stamper=null;
        try {
            String[] spe = PDFDataUtil.separatePath(inputFile);
            outputFile = spe[0] + "_WM." + spe[1];

            reader = new PdfReader(inputFile);
            stamper = new PdfStamper(reader, new FileOutputStream(outputFile));

            int total = reader.getNumberOfPages() + 1;

            Image image = Image.getInstance(imageFile);
            //坐标
            image.setAbsolutePosition(620, 460);
            //自定义大小
            image.scaleAbsolute(159,159);
            //image.setRotation(-20);//旋转 弧度
            //image.setRotationDegrees(-45);//旋转 角度
            //依照比例缩放
            image.scalePercent(76);

            PdfGState gs = new PdfGState();
            // 设置透明度为0.2
            gs.setFillOpacity(0.5f);


            PdfContentByte under;
            //给每一页加水印
            for (int i = 1; i < total; i++) {
                under = stamper.getUnderContent(i);
                under.beginText();
                // 添加水印图片
                under.addImage(image);
                under.setGState(gs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	if(null!=stamper){
                try {
					stamper.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        	if(null!=reader){
                try {
                	reader.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        }
        return outputFile;
    }

    public PdfPTable createDataTable() throws Exception{
        // 创建一个有4列的表格
        PdfPTable table = new PdfPTable(20);
        //设置列宽
        table.setTotalWidth(new float[]{22.63083f,39.27115f,61.89881f,81.20474f,16.640316f,21.302767f,37.939922f,39.936756f,37.27431f,40f,28.621342f,37.27431f,39.936756f,36.608696f,40.60237f,36.608696f,39.936756f,37.27431f,39.936756f,36.608696f});
        //锁定列宽
        table.setLockedWidth(true);

        return table;
    }

    private void drawTitle(BaseFont bfChinese,PdfPTable table) throws DocumentException, IOException{
    	/**
         * 设置表头
         */

        //添加中文字体bfHelvetica
        Font font = new Font(bfChinese,8,Font.NORMAL);

        //第一行
        createHeaderCell(table,new TableHeaderCell("序号",55,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("社保个人\n编码",55,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("姓名",55,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("社会保障号码\n（身份证号）",55,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("性\n别",55,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("人员\n缴费\n类别",55,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("申报工资",55,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("城镇职工养老保险",24,1,2,font),false,true);
        createHeaderCell(table,new TableHeaderCell("城镇职工医疗保险",24,1,3,font),false,true);
        createHeaderCell(table,new TableHeaderCell("失业保险",24,1,2,font),false,true);
        createHeaderCell(table,new TableHeaderCell("工伤保险",24,1,2,font),false,true);
        createHeaderCell(table,new TableHeaderCell("生育保险",24,1,2,font),false,true);
        createHeaderCell(table,new TableHeaderCell("大病医疗互助\n补充保险",24,1,2,font),true,true);

        //第二行
        createHeaderCell(table,new TableHeaderCell("本单位\n参保日期",32,1,1,font));
        createHeaderCell(table,new TableHeaderCell("缴费\n基数",32,1,1,font));

        createHeaderCell(table,new TableHeaderCell("本单位\n参保日期",32,1,1,font));
        createHeaderCell(table,new TableHeaderCell("类别",32,1,1,font));
        createHeaderCell(table,new TableHeaderCell("缴费\n基数",32,1,1,font));

        createHeaderCell(table,new TableHeaderCell("本单位\n参保日期",32,1,1,font));
        createHeaderCell(table,new TableHeaderCell("缴费\n基数",32,1,1,font));

        createHeaderCell(table,new TableHeaderCell("本单位\n参保日期",32,1,1,font));
        createHeaderCell(table,new TableHeaderCell("缴费\n基数",32,1,1,font));

        createHeaderCell(table,new TableHeaderCell("本单位\n参保日期",32,1,1,font));
        createHeaderCell(table,new TableHeaderCell("缴费\n基数",32,1,1,font));

        createHeaderCell(table,new TableHeaderCell("本单位\n参保日期",32,1,1,font));
        createHeaderCell(table,new TableHeaderCell("缴费\n基数",32,1,1,font),true,false);
    }


}

